<?php
namespace App\Modules\Relationship\Models;


use App\Http\Services\CommonServices;
use App\Modules\Relationship\Interfaces\ModelInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Base;

class CoupleReqModel extends Base{

    protected $table = "coupling_req";
    protected $fields = ['id', 'user_id as userId', 'req_user_id as reqUserId',
        'keepsake_id as keepsakeId', 'req_count as reqCount', 'last_timestamp as lastTimestamp',
        'last_time as lastTime', 'expire_time as expireTime','is_deleted as isDeleted'
        ];

    public function __construct(array $attributes = []){
        parent::__construct($this->table, $attributes);
        $this->tablePrefix = env('DB_PREFIX');
    }


    // 24小时内有没有请求过
    public function getReqWithin24hours($userId, $reqUserId) {
        $table = $this->tablePrefix . $this->table;
        $fields = implode(',', $this->fields);
        $timeInt = date("Y-m-d H:i:s",time()- 24 * 60 * 60);
        $sql = "select {$fields} from {$table} where user_id = ? and req_user_id=? and expire_time > ?";
        $bindings = [$userId, $reqUserId, $timeInt];
        $rows = DB::select($sql, $bindings);
        if (!$rows) {
            return null;
        }
        return $rows;
    }

    public function getOneRecord ($userId, $friendId) {
        $condition =  array(
            'user_id'=>$userId,
            'req_user_id'=>$friendId,
            'is_deleted'=>0
        );
        return $this->getOneByCondition($condition, $this->fields);
    }

    public function getOneRecordById ($id) {
        $condition =  array(
            'id'=>$id
        );
        return $this->getOneByCondition($condition, $this->fields);
    }

    public function getOneRecordByFriendId ($userId, $friendId) {
        $condition =  array(
            'user_id'=>$friendId,
            'req_user_id'=>$userId,
            'is_deleted'=>0
        );
        return $this->getOneByCondition($condition, $this->fields);
    }

    public function insertReq($userId, $friendId, $keepsakeId) {
        $data = array(
            "user_id"=>$userId,
            "req_user_id"=>$friendId,
            "keepsake_id"=>$keepsakeId,
            "req_count"=>1,
            "last_timestamp"=>time(),
            "expire_time"=>date("Y-m-d H:i:s",(time() + 24 * 60 * 60))
        );

        $re = DB::table($this->table)->insertGetId($data);
        return $re;
    }

    public function deleteReq (int $id) {
        return DB::table($this->table)->where('id',  $id)->delete();
    }
}

